package reflectionAndAnnotation.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/24 12:46
 */
public class Field {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //创建class对象
        Class<?> aClass = Class.forName("reflectionAndAnnotation.reflection.model.User");

        //获得所有字段（公共）
        java.lang.reflect.Field[] fields = aClass.getFields();
        for (java.lang.reflect.Field field : fields) {
            System.out.println(field);
        }
        System.out.println();
        //私有
        java.lang.reflect.Field[] declaredFields = aClass.getDeclaredFields();
        for (java.lang.reflect.Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        System.out.println();

        //获得单个字段(公共)
        java.lang.reflect.Field age = aClass.getField("age");
        System.out.println(age);
        System.out.println();
        //私有
        java.lang.reflect.Field name = aClass.getDeclaredField("name");
        System.out.println(name);
        System.out.println();

        //创建User对象
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(int.class);
        //暴力反射
        declaredConstructor.setAccessible(true);
        name.setAccessible(true);
        Object o = declaredConstructor.newInstance(20);
        //给o对象的name设置值为周
        name.set(o,"周");
        System.out.println(o);
        System.out.println();

    }
}
